package com.john.market.classes;

import java.util.ArrayList;
import java.util.UUID;

import com.john.market.interfaces.IUpdatable;

import android.app.ListActivity;

public class UpdatableListActivity extends ListActivity implements IUpdatable {
	// List of the products
	protected ArrayList<Product> mProductList = new ArrayList<Product>();
	
	// Adapter for the ListView
	protected ProductAdapter mAdapter = null;
	
	/**
	 * Gets position of product in list by its ID  
	 * 
	 * @param id
	 * ID of the product	
	 * 
	 * @return
	 * Position of the product in the list
	 * 
	 */
	public int getProductPos(UUID id) {
		synchronized (this.mProductList) {
			int size = this.mProductList.size();
			if (size == 0) return -1;
			
			// Bypassing the list of products
			for (int i = 0; i < size; ++i) {
				Product product = this.mProductList.get(i); 
				if (id.equals(product.getId())) {
					return i;
				}
			}
		}
		
		return -1;
		
	}
	
	// Update ListView content
	private synchronized void notifyDataSetChanged() {
		this.mAdapter.notifyDataSetChanged();
		
	}
	
	@Override
	public void onPurchased(UUID id, int amount) {
		synchronized (this.mProductList) {
			// Getting position of the product in the list
			int pos = getProductPos(id);
			
			if (pos != -1) {
				this.mProductList.get(pos).setAmount(amount);
			}
				
			this.mAdapter.enableButton(id);
		}	
		
		notifyDataSetChanged();
		
	}

	@Override
	public void onUpdated(Product product) {
		synchronized (this.mProductList) {
			// Getting position of the product in the list
			UUID id = product.getId();
			int pos = getProductPos(id);
			
			// Adding or updating the product
			if (pos != -1) {
				this.mProductList.set(pos, product);
			}
			else {
				this.mProductList.add(product);
			}
		}
		
		notifyDataSetChanged();
		
	}

	@Override
	public void onRemoved(UUID id) {
		synchronized (this.mProductList) {
			// Getting position of the product in the list
			int pos = getProductPos(id);
			if (pos == -1) return;
			
			// Removing the product
			this.mProductList.remove(pos);
			this.mAdapter.enableButton(id);
		}
		
		notifyDataSetChanged();
		
	}
	
	@Override
	public void onNeedRefresh() {
		notifyDataSetChanged();
		
	}
	
}
